package com.kehongborui.servletinitparam;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-17
 */
public class ServletInitDemo implements Servlet {
    private String initParam = "1";
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println(servletConfig.getInitParameter("company"));
        System.out.println(servletConfig.getInitParameter("author"));
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
//        servletConfig.getInitParameter();
        ServletContext servletContext = servletRequest.getServletContext();
        // 获取全局变量中count属性
        if (servletContext.getAttribute("count") == null) {
            servletContext.setAttribute("count", (Integer.parseInt(servletContext.getInitParameter("count")) + 1));
        } else {
            servletContext.setAttribute("count", ((int)servletContext.getAttribute("count")) + 1);
        }

        // 解决 response 乱码
        servletResponse.setContentType("text/html;charset=UTF-8");
        // 获取向浏览器输出数据的打印流
        PrintWriter writer = servletResponse.getWriter();
        writer.println("<h1>test</h1>");
        // 关闭打印流
        writer.close();
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
